<?php

/**
 * 文件目录操作
 */
class BuildHelper
{
    static public function make($dir, $mode=0775, $type = true)
    {
        return is_dir($dir) or
                ( make( dirname($dir) , $mode, $type ) and
                @mkdir($dir, $mode, $type));
    }

    static public function getFileList($root, $basePath = '')
    {
        $files = [];
        $handle = opendir($root);

        while (($path = readdir($handle)) !== false) {
            if ($path === '.svn' || $path === '.' || $path === '..') {
                continue;
            }

            $fullPath = "$root/$path";
            $relativePath = $basePath === '' ? $path : "$basePath/$path";

            if (is_dir($fullPath)) {
                $files = array_merge($files, getFileList($fullPath, $relativePath));
            } else {
                $files[] = $relativePath;
            }
        }
        closedir($handle);
        return $files;
    }

    /**
     * @param $root string 基准目录
     * @param $source string 来源文件
     * @param $target string 目标文件
     * @param $all
     * @param $params
     * @return bool
     */
    static public function copyFile($root, $source, $target, &$all, $params)
    {
        if (!is_file($root . '/' . $source)) {
            echo "       skip $target ($root/$source not exist)\n";
            return true;
        }

        if (is_file($root . '/' . $target)) {
            // 文件没有任何改动，跳过
            if (file_get_contents($root . '/' . $source) === file_get_contents($root . '/' . $target))
            {
                echo "      unchanged $target\n";
                return true;
            }

            if ($all) {
                echo "      overwrite $target\n";
            } else {
                echo "      exist $target\n";
                echo "            ...overwrite? [Yes|No|All|Quit] ";


                $answer = !empty($params['overwrite']) ? $params['overwrite'] : trim(fgets(STDIN));

                if (!strncasecmp($answer, 'q', 1))
                {
                    return false;
                } else {

                    if (!strncasecmp($answer, 'y', 1)) {
                        echo "  overwrite $target\n";
                    } else {
                        if (!strncasecmp($answer, 'a', 1)) {
                            echo "  overwrite $target\n";
                            $all = true;
                        } else {
                            echo "       skip $target\n";
                            return true;
                        }
                    }
                }
            }

            file_put_contents($root . '/' . $target, file_get_contents($root . '/' . $source));
            return true;
        }
        echo "   generate $target\n";
        @mkdir(dirname($root . '/' . $target), 0777, true);
        file_put_contents($root . '/' . $target, file_get_contents($root . '/' . $source));
        return true;
    }

} // end class